<template>
  <div class="user">
    <el-form label-position="top" ref="ruleFormRef" :model="fromData" :rules="rules">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="fromData.name"/>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="fromData.age" type="number" min="1" max="100"/>
      </el-form-item>
      <div>
        <el-button type="primary" @click="submitForm(ruleFormRef)">添加</el-button>
        <el-button type="danger" @click="resetForm(ruleFormRef)">重置</el-button>
      </div>
    </el-form>

    <div>
      <h1>用户信息表</h1>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="id" label="ID" width="150"/>
        <el-table-column prop="name" label="项目"/>
        <el-table-column prop="age" label="年龄"/>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="tableData.splice(scope.$index,1)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

  </div>
</template>
<script setup lang="ts">
import {ref, reactive} from "vue";
import type {FormInstance} from "element-plus";

const ruleFormRef = ref<FormInstance>()
const rules = reactive({
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
  ],
  age: [
    {required: true, message: '请输入年龄', trigger: 'blur'},
  ],
})

interface userType {
  id: number,
  name: string,
  age: number,
}

const fromData = ref<userType>({
  id: 0,
  name: "",
  age: 0,
})

const tableData = ref<userType[]>([
  {
    id: 0,
    name: "小乔大王",
    age: 10
  }
])

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      fromData.value.id = tableData.value[tableData.value.length - 1].id + 1
      console.log(fromData.value)
      tableData.value.unshift({...fromData.value})
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped>
.user {
  padding: 10px;
  width: 100%;
  height: 100%;
}
</style>